
<template>
  <el-tag
    :key="tag"
    v-for="tag in dynamicTags"
    closable
    :disable-transitions="false"
    @close="handleClose(tag)"
    class="my-tag"
  >
    {{ tag.name }}
  </el-tag>
  <el-alert v-show="showAlert" title="标签已存在" type="error"></el-alert>
  <el-input
    class="input-new-tag"
    v-if="inputVisible"
    v-model="inputValue"
    ref="saveTagInput"
    size="small"
    @keyup.enter.native="handleInputConfirm"
    @blur="handleInputConfirm"
  >
  </el-input>
  <el-button v-else class="button-new-tag" size="small" @click="showInput"
    >+ New Tag</el-button
  >
</template>

<script>
import { getTags, addTag, deleteTag } from "../../api/tags.js";
export default {
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      showAlert: false,
    };
  },
  mounted() {
    this.getDynamicTags();
  },
  methods: {
    getDynamicTags() {
      getTags().then((res) => {
        this.dynamicTags = res.data;
      });
    },
    handleClose(tag) {
      deleteTag(tag.id).then(() => {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      });
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        let tags_name = [];
        for (let tag of this.dynamicTags) {
          tags_name = [...tags_name, tag.name];
        }
        if (tags_name.indexOf(inputValue) != -1) {
          this.showAlert = true;
          return;
        }
        this.showAlert = false;
        let newTag;
        addTag({ name: inputValue }).then((res) => {
          newTag = res.data;
          this.dynamicTags.push(newTag);
          this.inputVisible = false;
          this.inputValue = "";
        });
      }
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
